app.component('createReqDesign', {
    templateUrl: getTemplateUrl('matrix/component/tpl/createReqDesign.html'),
    bindings: {
        type      : "@",  //1：new  2: induction  3：tab
        trList    : "=",  //选中的tr列表
        saveFun   : "&",  //保存方法
        cancelFun : "&",  //取消方法
    },
    controller: function($scope, $rootScope, $http, $filter, $stateParams, lodash) {
        var ctrl = this;
        $scope.info={};
        $scope.designType = ctrl.type;
        $scope.radioStatus = "true";
        $scope.selectedUser = "";    //根据tr中的account，设置选中的指派对象
        $scope.userList = [];
        $scope.info.selectedReq = "";     //选中的内容数据
        $scope.searchType = [{"crtname": "内容查询", "type": true}, {"crtname": "编号查询", "type": false}];
        $scope.searchTypeItem = {"crtname": "内容查询", "type": true};
        $scope.isChecked = true;
        $scope.isCreatePP = false;
        $scope.design = {
            productLineId: "",
            title: "",
            desc : "",
        };

        if(ctrl.type == "tab") {
            getIssuesByReqId();
        }
        if(ctrl.type != "tab") {
            getProductLineById();
        }
        initValue();
        getIssues();
        getUserList();

        $scope.showAlert = false;

        $scope.showAlertMessage = function() {
            $scope.showAlert = !$scope.showAlert;
        };

        function initValue() {
            if(ctrl.type == "induction") {
                angular.forEach(ctrl.trList, function(tr) {
                    tr.sltUser = {"user": tr.user, "crtname": tr.user};
                });
                $scope.selectedTrData = ctrl.trList;
            } else {
                $scope.selectedTrData = [];
            }
            angular.forEach(issueUser, function(user) {
                user.crtname = user.name;
            });
            $scope.issueUser = issueUser;
        };

        $scope.selectProductLine = function(item, selectedItems) {
            console.log(item);
            //console.log(selectedItems);
            $scope.design.productLineId = item.id;
        };

        function getProductLineById() {
            var url = matrix_product_url +"/productLine/getProductLineTree";
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    $scope.levelLine0 = result.data ? result.data.children : "";
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };

        function getIssuesByReqId() {
            var url = matrix_product_url +"/issue/getReqIssues?reqId="+ $stateParams.reqId;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    $scope.selectedTrData = result.data;
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };

        function getIssues() {
            var url = matrix_product_url +"/issue/getIssues";
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    $scope.reqList = result.data;
                    angular.forEach(ctrl.trList, function(tr) {
                        lodash.remove($scope.reqList, function(req) {
                            return req.number == tr.number;
                        });
                    });
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        }
    
        //获取用户集合（设置指派对象）
        function getUserList() {
            var url = beetle_auth_url +"/user/?token_id=" + getTokenId();
            $http.get(url).success(function(result) {
                if(result.success) {
                    $scope.info.selectedReq = "";
                    if(result.data) {
                        $scope.userList   = result.data;
                        angular.forEach($scope.selectedTrData, function(val, index) {
                            val.index        = index;
                            val.sltUser      = {"user": val.user, "crtname": val.user};
                            val.sltToAccount = lodash.findWhere(result.data, {account: val.toAccount});
                        });
                    } else {
                        $rootScope.toasterErrorInfo("获取用户数据错误！");
                    }
                } else {
                    $rootScope.toasterErrorInfo(result.msg);
                }
            });
        };
    
        //设置下拉框选中值
        $scope.clickSelectedReq = function(item) {
            $scope.info.selectedReq = item;
        };
    
        //将下拉框中的选中值添加到tr数组中
        $scope.addTrBySelectedReq = function() {
            if($scope.info.selectedReq.number == undefined) {
                $rootScope.toasterWarningInfo("请选择数据！");
                return false;
            }
            $scope.info.selectedReq.sltUser = lodash.findWhere(issueUser, {"name": $scope.info.selectedReq.user});
            $scope.info.selectedReq.sltToAccount = lodash.findWhere($scope.userList, {account: $scope.info.selectedReq.toAccount});
            $scope.info.selectedReq.user = $scope.info.selectedReq.user;
            if(!$scope.selectedTrData) {
                $scope.selectedTrData = [];
            }
            $scope.info.selectedReq.index = $scope.selectedTrData.length == 0 ? 0 : $scope.selectedTrData.length;
            $scope.info.selectedReq.isSave = false;
            $scope.selectedTrData.push($scope.info.selectedReq);
            lodash.remove($scope.reqList, function(req) {
                return req.number == $scope.info.selectedReq.number;
            });
            $scope.info.selectedReq = "";
        };
    
        //选择指派对象
        $scope.selectToAccount = function(trData) {
            console.log("selectToAccount");
            console.log(trData);
        };

        //选择用户
        $scope.selectUserItem = function(item) {
            angular.forEach($scope.selectedTrData, function(reqData) {
                if(reqData.number == item.data.number) {
                    reqData.user = item.name;
                }
            });
        };
    
        //添加行
        $scope.addTr = function(trData) {
            var url = matrix_product_url +"/issue/getIssueNumber";
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    if(result.data) {
                        if(!$scope.selectedTrData) {
                            $scope.selectedTrData = [];
                        }
                        var initData = {"index": $scope.selectedTrData.length, "number": result.data, "user": "卖家", "sltUser": {"name": "卖家", "crtname": "卖家"}, "action": "", "description": "", "toAccount": getUserAccount(), "sltToAccount": {"account": getUserAccount(), "realname": getUserName(), "id": getUserId()}};
                        $scope.selectedTrData.push(initData);
                    } else {
                        $rootScope.toasterErrorInfo("获取IssueCode失败！");
                    }
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };
    
        //删除行
        $scope.clickDeleteBtn = function(trData) {
            lodash.remove($scope.selectedTrData, {index: trData.index});
            $scope.reqList.push(trData)
        };
    
        $scope.checkboxChange = function(isChecked) {
            $scope.isChecked = isChecked;
        };
    
        $scope.checkboxPPChange = function(isCreatePP) {
            $scope.isCreatePP = isCreatePP;
        };

        //上移数据
        $scope.setPrevTr = function(trData) {
            if(trData.index == 0) {
                return false;
            }
            var prevTr = lodash.findWhere($scope.selectedTrData, {index: trData.index-1});
            prevTr.index ++;
            trData.index --;
            $scope.selectedTrData = lodash.sortByOrder($scope.selectedTrData, ['index']);
        };

        //下移数据
        $scope.setNextTr = function(trData) {
            if($scope.selectedTrData.length == trData.index+1) {
                return false;
            }
            var nextTr = lodash.findWhere($scope.selectedTrData, {index: trData.index+1});
            nextTr.index --;
            trData.index ++;
            $scope.selectedTrData = lodash.sortByOrder($scope.selectedTrData, ['index']);
        };

        function createProjectPlan(number, dataAttr) {
            var postParams = {
                tokenId:  getTokenId(),
                projectPlanName: dataAttr.design.title,
                projectPlanDesc: dataAttr.design.desc,
                projectPlanStatus: "NEW",
                //projectPlanNo: number,
                //projectPlanCode: code,
            };
            var url = matrix_product_url +"/projectPlan/saveProjectPlan";
            $http({
                method  : "post",
                url     : url,
                data    : JSON.stringify(postParams),
                headers : {"Content-Type": "application/json"}
            }).success(function(result) {
                if(result.code == "0") {
                    $rootScope.toasterSuccessInfo("项目计划创建成功");
                    ctrl.saveFun({data: dataAttr});
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };
    
        $scope.createClick = function() {
            angular.forEach($scope.selectedTrData, function(tr) {
                if(tr.sltUser) {
                    tr.user = tr.sltUser.name;
                    //if(ctrl.type != "tab") {
                    //    delete tr.user;
                    //}
                }
                if(tr.sltToAccount) {
                    tr.toAccount = tr.sltToAccount.account;
                    //if(ctrl.type != "tab") {
                    //    delete tr.sltToAccount;
                    //}
                }
                tr.creatorAccount = getUserAccount();
                // tr.createTime = $filter('date')(new Date(), 'yyyy-MM-dd ');
            });
            var dataAttr = {
                type      : ctrl.type,
                design    : $scope.design,
                isChecked : $scope.isChecked,
                isCreatePP: $scope.isCreatePP,
                trData    : $scope.selectedTrData,
            }
            ctrl.saveFun({data: dataAttr});
        };
    
        $scope.cancelClick = function() {
            lodash.remove($scope.selectedTrData, function(sltTr) {
                return sltTr.id == null || sltTr.id == undefined;
            });
            ctrl.cancelFun();
        };
    }
});